package com.shop.cloud.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.cloud.common.core.constant.CacheConstants;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.constant.SecurityConstants;
import com.shop.cloud.common.core.exception.ValidateCodeException;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.core.util.WebUtils;
import com.shop.cloud.gateway.config.GatewayConfigProperties;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author
 * 验证码处理
 */
@Slf4j
@AllArgsConstructor
public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
	private final GatewayConfigProperties configProperties;

	private final ObjectMapper objectMapper;

	private final RedisTemplate<String, Object> redisTemplate;

	@Override
	public GatewayFilter apply(Object config) {
		return (exchange, chain) -> {
			ServerHttpRequest request = exchange.getRequest();

			// 不是登录请求，直接向下执行
			if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath()
					, SecurityConstants.OAUTH_TOKEN_URL) ) {
				return chain.filter(exchange);
			}

			// 刷新token、第三方登录，直接向下执行
			String grantType = request.getQueryParams().getFirst("grant_type");
			if (StrUtil.equals(SecurityConstants.REFRESH_TOKEN, grantType) || StrUtil.equals(SecurityConstants.THIRD_PARTY, grantType)) {
				return chain.filter(exchange);
			}

			// 终端设置不校验， 直接向下执行
			boolean isIgnoreClient = configProperties.getIgnoreClients().contains(WebUtils.getClientId(request));
			try {
				if (!isIgnoreClient) {
					checkCode(request);
				}
			} catch (Exception e) {
				ServerHttpResponse response = exchange.getResponse();
				response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
				try {
					return response.writeWith(Mono.just(response.bufferFactory()
							.wrap(objectMapper.writeValueAsBytes(
									R.failed(e.getMessage())))));
				} catch (JsonProcessingException e1) {
					log.error("对象输出异常", e1);
				}
			}

			return chain.filter(exchange);
		};
	}

	/**
	 * 检查code
	 *
	 * @param request
	 */
	@SneakyThrows
	private void checkCode(ServerHttpRequest request) {
		String code = request.getQueryParams().getFirst("code");

		if (StrUtil.isBlank(code)) {
			throw new ValidateCodeException("验证码不能为空");
		}

		String randomStr = request.getQueryParams().getFirst("randomStr");
		String grantType = request.getQueryParams().getFirst("grant_type");
		if (StrUtil.equals(SecurityConstants.SMS_LOGIN, grantType)) {
			randomStr = CommonConstants.PHONE_CODE_1 + ":" + request.getQueryParams().getFirst("phone");
		}

		String key = CacheConstants.VER_CODE_DEFAULT + randomStr;
		redisTemplate.setKeySerializer(new StringRedisSerializer());

		if (!redisTemplate.hasKey(key)) {
			throw new ValidateCodeException("验证码不合法");
		}

		Object codeObj = redisTemplate.opsForValue().get(key);

		if (codeObj == null) {
			throw new ValidateCodeException("验证码不合法");
		}

		String saveCode = codeObj.toString();
		if (StrUtil.isBlank(saveCode)) {
			redisTemplate.delete(key);
			throw new ValidateCodeException("验证码不合法");
		}

		if (!StrUtil.equals(saveCode, code)) {
			//如果是短信验证码登录，记录失败次数，失败3次强制作废当前验证码，防止短信验证码爆破
			if (StrUtil.equals(SecurityConstants.SMS_LOGIN, grantType)) {
				String key2 = CacheConstants.VER_CODE_DEFAULT + CommonConstants.SMS_LOGIN_FAILURES + ":" + request.getQueryParams().getFirst("phone");
				if (!redisTemplate.hasKey(key2)) {
					redisTemplate.opsForValue().set(key2, 1, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
				}else{
					int times = (int) redisTemplate.opsForValue().get(key2);
					if(times < 3){
						redisTemplate.opsForValue().set(key2, times+1, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
					}else{
						//失败3次强制作废当前验证码
						redisTemplate.delete(key);
						redisTemplate.delete(key2);
						throw new ValidateCodeException("该验证码已超过提交次数已作废，请重新获取");
					}
				}
			}
			throw new ValidateCodeException("验证码不合法");
		}

		redisTemplate.delete(key);
	}
}
